import { generateRouteConfig } from "@whzhuke/components"
import React from "react"
import ReactDOM from "react-dom/client"
import { createBrowserRouter, RouterProvider } from "react-router-dom"
import "@/css/global.css"
import PageLoading from "@/components/utils/PageLoading"
import { message } from "antd"
import { StoreContextDefault } from "@/store/index"
import { useFetch } from "@whzhuke/usehook"
import { lsCommon } from "@whzhuke/common"
declare global {
  namespace localStorageData {
    interface data {
      token: string
    }
  }
  interface Window {
    message?: {
      error: (content: string) => void
    }
  }
}
// 将 message 挂载到 window 上，供请求库使用
window.message = message as any
/**
 * 请求处理
 */
window.interceptorsRequest = config => {
  config.headers.set("Authorization", `${lsCommon.getItem("token")}`)
  return config
}
window.interceptorsResponse = result => {
  if (result.config.url?.includes(".json")) return result

  // 处理 HTTP 状态码错误（如 404, 500 等）
  if (result.status && result.status >= 400) {
    const statusText = result.statusText || "请求失败"
    message.error(`${result.status} ${statusText}`)
    throw `${result.config.url} ${result.status} ${statusText}`
  }

  const data: any = result.data
  if ("code" in data) {
    // 成功状态码，直接返回
    if (data.code === 200) {
      return result
    }
    // 处理特殊错误码
    if (data.code === -1000) {
      StoreContextDefault.UserStore.setUser(null)
    }
    // 显示错误提示（确保有提示信息）
    const errorMessage = data?.message || data?.msg || `请求失败，错误码：${data.code}` || "接口异常"
    message.error(errorMessage)
    throw `${result.config.url} ${errorMessage}`
  } else {
    return result
  }
}

/**
 * 路由处理
 */
const build = generateRouteConfig({ pages: import.meta.glob([`./pages/**/*.{ts,tsx}`]), loading: PageLoading })
const router = createBrowserRouter(build)

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
)
